<?php
namespace app\adminapi\controller;

use think\Controller;

class Upload extends BaseApi
{
    /**
     * 单图片上传
     *
     * @return void
     * 
     */
		public function logo(){
				$type = input('type');
        if(empty($type)){
            $this->fail('参数错误',402,'');
        }
        $file = request()->file('logo');
        if(empty($file)){
            $this->fail('必须上传文件',403,'');
        }
        $info = $file->validate(['size' => 10*1024*1024, 'ext' => 'jpg,jpeg,png,gif'])
                ->move(ROOT_PATH . 'public'. DS . 'uploads'. DS . $type);
        if($info){
            $src = DS .'uploads'. DS .'category'. $info->getSaveName();
            $this->ok($src);
        }
        $error = $file->getError();
        $this->fail($error);			
			
		}
    /**
     * 多图片上传
     *
     * @return void
     */	
		public function images(){
			//接收type参数, 图片分组
			$type = input('type','goods');
			//获取上传的文件
			$files = request()->file('images');
			//遍历数组逐个上传文件
			$data = ['success'=>[],'error'=>[]];
			foreach($files as $file){
				//移动文件到指定目录下
				$dir = ROOT_PATH . 'public'. DS . 'uploads'. DS . $type;
				if(!is_dir($dir)){
					mkdir($dir);
				}	
				$info = $file->validate(['size' => 10*1024*1024, 'ext' => 'jpg,jpeg,png,gif'])->move($dir);
				if($info){
					//成功拼接图片路径
					$path = DS . 'uploads'. DS . $type . DS . $info->getSaveName();
					$data['success'][] = $path;							
				} else {
				  //失败获取错误信息
				  $data['error'][] = [
					 'name' => $file->getInfo('name'),
					 'msg' => $file->getError()
				  ];
				}
			}
			$this->ok($data);
		}
}
